package common.currentLimiting;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;

/**
 * 滑动窗口限流
 *
 * @author K
 * @date 2024-04-02 22:31
 */
public class SlidingWindowLimiter {
    /**
     * 所有请求时间队列
     */
    private static Queue<Long> times = new LinkedList<>();
    /**
     * 窗口大小，时间范围(毫秒)
     */
    private static int windowSize = 3000;
    /**
     * 限制的请求数量
     */
    private static int limitCount = 20;


    public synchronized static boolean tryAcquire() {
        long now = System.currentTimeMillis();
        times.offer(now);
        while (times.peek() + windowSize < now) {
            times.poll();
        }

        return times.size() <= limitCount;
    }

    public static void main(String[] args) throws InterruptedException {
        Random random = new Random();
        while (true){
            boolean b = tryAcquire();
            Thread.sleep(random.nextInt(300));
            System.out.println(b);
        }
    }
}
